<template>
  <div class="like-btn" :class="{ zoom }" @click="toggleLike" @animationend="onAnimEnd">
    <Icon v-if="isLike" size="36" shadow name="heartActive"></Icon>
    <Icon v-else size="36" shadow name="likeBold"></Icon>
    <span class="font-size-12 font-weight-500">{{ toKMBTString(likeCount) }}</span>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useAccountStore } from '@/store/account'
import { useSubscribeTipStore } from '@/store/subscribe-tip'
import { notifyLike } from '@/utils/state-broadcast'
import { toKMBTString } from '@/utils/string-helper'
import { trackEvent } from '@/gtm'
import API from '@/http'

const props = defineProps({
  id: { type: Number, required: true },
  aff: { type: Number, required: true },
  isLike: { type: Boolean, required: true },
  likeCount: { type: Number, required: true },
})

let selfTriggerLike = false
const { trigger, clear } = useSubscribeTipStore()
function $toggleLike() {
  selfTriggerLike = true

  // 通知所有地方此文點讚
  notifyLike(props.id, !props.isLike)

  // 打後端API
  const toggler = props.isLike ? API.Home.unlike : API.Home.like
  if ($toggleLike.controller) {
    $toggleLike.controller.abort()
  }
  $toggleLike.controller = new AbortController()
  toggler({
    data: { mv_id: props.id },
    config: { signal: $toggleLike.controller.signal },
  }).catch((e) => console.warn('Toggle feed like fail: ', e))
  if (toggler === API.Home.like) {
    trigger(props.aff)
  } else {
    clear()
  }
}
const { afterLoginAction } = useAccountStore()
const toggleLikeAfterLogin = afterLoginAction($toggleLike)
function toggleLike() {
  if (!props.isLike) {
    trackEvent({ key: 2, meta: { id: props.id } })
  }
  toggleLikeAfterLogin()
}

// 雙擊事件點讚愛心特效
const zoom = ref(false)
watch(
  () => props.isLike,
  (v) => {
    if (v && !selfTriggerLike) {
      zoom.value = true
    }
    selfTriggerLike = false
  },
)
function onAnimEnd() {
  zoom.value = false
}
</script>

<style lang="scss" scoped>
@keyframes shake {
  0% {
    transform: rotate(0deg);
  }
  22% {
    transform: scale(1.1) rotate(-10deg);
  }
  45% {
    transform: scale(1.1) rotate(-20deg);
  }
  90% {
    transform: scale(1.1) rotate(5deg);
  }
  100% {
    transform: scale(1.1) rotate(0deg);
  }
}

@keyframes zoom {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.5);
    opacity: 0.5;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

.zoom .icon {
  animation: zoom 0.5s ease 0s 1 forwards;
}

.desktop {
  .like-btn {
    &:hover .icon {
      animation: shake 0.5s ease 0s 1 forwards;
      transform-origin: bottom;
    }
  }
}
</style>
